package com.my12306.common.util.quartz.scheduler;

import com.google.gson.Gson;
import com.my12306.common.model.po.ScheduleJobPo;
import com.my12306.common.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;

import java.text.ParseException;

/**
 * cron表达式任务调度类
 *
 * @Author:苏牧夕
 * @Date:2020/5/29 2:16
 * @Version 1.0
 */
@Slf4j
@Component
public class CronScheduler extends AbstractScheduler {

    public static void main(String[] args) throws ParseException {
        String corn = "0 0 0 * * ? 2020";
        boolean validExpression = CronExpression.isValidExpression(corn);
        System.out.println(validExpression);
        String corn2 = "0/5 * * * 6 ? 2020";
        System.out.println(CronExpression.isValidExpression(corn2));
    }
    public void addJob(Scheduler scheduler, ScheduleJobPo scheduleJobPo, JobKey jobKey, TriggerKey triggerKey) throws SchedulerException {
//        try {
        //通过spring获取对应的bean，然后通过反射获取类型
        JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>) SpringContextUtils.getBean(scheduleJobPo.getBeanName()).getClass())
                .withIdentity(jobKey)
                .withDescription(scheduleJobPo.getJobDesc())
                .build();
        Gson gson = new Gson();
        System.out.println("=========>定时任务参数"+scheduleJobPo.getParams());
        // TODO: 2020/5/30 待写真正业务
        String params = scheduleJobPo.getParams();
        if (params!=null) {
            jobDetail.getJobDataMap().put("data", gson.toJson(params));
        }
        jobDetail.getJobDataMap().put("job", gson.toJson(scheduleJobPo));

        log.info("=====================>cronScheduleBuilder之前：");
        //通过cron表达式建造者类创建Cron表达式
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJobPo.getCronExpression());
        log.info("=====================>cronScheduleBuilder之后：");
        //创建一个cron表达式的触发器并且配置触发器的唯一身份，
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey)
                .withSchedule(cronScheduleBuilder).build();
        log.info("============》开始定时任务之前");
        //通过调度器，把任务和触发器关联起来并开始调度任务
        scheduler.scheduleJob(jobDetail, trigger);
        log.info("==================>已经开始定时任务");
//        } catch (SchedulerException e) {
//            try {
//                throw new SchedulerException("创建定时任务失败！",e);
//            } catch (SchedulerException ex) {
//                throw new RTExcption("创建任务系统异常！",ex);
//            }
//        }
    }

    public void updateJob(Scheduler scheduler, ScheduleJobPo scheduleJobPo, TriggerKey triggerKey) throws SchedulerException {
        //重新构建cron表达式
        System.out.println("修改：========》" + scheduleJobPo);
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJobPo.getCronExpression())
                .withMisfireHandlingInstructionDoNothing();
        CronTrigger trigger = null;
//        try {

        trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
                .withSchedule(cronScheduleBuilder).build();
        // TODO: 2020/5/30 需要修改
        String params = scheduleJobPo.getParams();
        if (params!=null) {
            trigger.getJobDataMap().put("data",params );
        }
        scheduler.rescheduleJob(triggerKey, trigger);
//        } catch (SchedulerException e) {
//            try {
//                throw new SchedulerException("修改定时任务失败",e);
//            } catch (SchedulerException ex) {
//                ex.printStackTrace();
//            }
//        }

    }

}
